package xyz.kongbai121.shop.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xyz.kongbai121.common.utils.HttpUtils;
import xyz.kongbai121.common.utils.R;
import xyz.kongbai121.common.vo.MemberRespVo;
import xyz.kongbai121.shop.auth.feign.MemberFeignService;
import xyz.kongbai121.shop.auth.vo.GiteeUserInfo;
import xyz.kongbai121.shop.auth.vo.SocialUser;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
        //1.根据code换取accessToken
        Map<String, String> map = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","51d885fc27444411d9e7d1c603e9dc3da3b83a89ad0bfe33948c35b87bbe2fd5");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret","55e3f57c0823c4d97d9000160032c386657a7a73ef433a733aff9ca1b9fe6a8b");
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, null, map);
        //获取到accessToken
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            GiteeUserInfo giteeUserInfo = giteeUserInfo(socialUser.getAccess_token());
            if (giteeUserInfo != null){
                giteeUserInfo.setAccess_token(socialUser.getAccess_token());
                giteeUserInfo.setExpires_in(socialUser.getExpires_in());
                R r = memberFeignService.oauthLogin(giteeUserInfo);
                if (r.getCode() == 0){
                    MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});
                    log.info("登录成功:用户信息{}",data);
                    session.setAttribute("loginUser",data);
                    return "redirect:http://gulimall.com";
                }
            }
        }
        HashMap<String, String> errors = new HashMap<>();
        errors.put("msg","登录失败");
        redirectAttributes.addFlashAttribute("msg",errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }


    /**
     * 获取gitee用户信息
     */
    private GiteeUserInfo giteeUserInfo(String accessToken) throws Exception {
        //1.根据code换取accessToken
        Map<String, String> map = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        map.put("access_token",accessToken);
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", headers, map);
        System.out.println(response);
        //获取到accessToken
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了token
            String json = EntityUtils.toString(response.getEntity());
            return JSON.parseObject(json, GiteeUserInfo.class);
        }else {
            return null;
        }
    }
}
